<?php
// +----------------------------------------------------------------------
// | CleverPHP [ WE CAN DO IT JUST BeautySoft ]
// +----------------------------------------------------------------------
// | Copyright (c) 2012~2017 http://git.oschina.net/ceiba/CleverPHP All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: ceiba <ceiba_@126.com>
// +----------------------------------------------------------------------

class SessionMemcache {
		private static  $handler=null;
		private static  $lifetime=null;
		private static  $time = null;
		public static  function init(){
			if(!array_key_exists("session_lifetime", C())){
				self::$lifetime=ini_get('session.gc_maxlifetime');
			}
			self::$time=time();
			self::$handler= new Memcache();
			$pro=C("memcache_prot")?C("memcache_prot"):11211;
			self::$handler->connect(C("memcache_host"), intval($pro));
			if (!self::$handler) {
				throw new Exception("Session驱动连接失败");
			}
			self::start();
		}
		public static  function start(){
			session_set_save_handler(
					array(__CLASS__, 'open'),
					array(__CLASS__, 'close'),
					array(__CLASS__, 'read'),
					array(__CLASS__, 'write'),
					array(__CLASS__, 'destroy'),
					array(__CLASS__, 'gc')
				);
			@session_start();
		}

	    /**
	     * 打开
	     * Enter description here ...
	     * @param unknown_type $path
	     * @param unknown_type $name
	     */
		public static  function open($path, $name){
			return true;
		}
        /**
         * 关闭
         * Enter description here ...
         */
		public static function close(){
			return true;
		}
        /**
         * 读取
         * Enter description here ...
         * @param unknown_type $PHPSESSID
         */
		public static function read($PHPSESSID){
			$out=self::$handler->get(self::session_key($PHPSESSID));
			if($out===false || $out == null)
				return '';
			return $out;
		}
        /**
         * 写入
         * Enter description here ...
         * @param unknown_type $PHPSESSID
         * @param unknown_type $data
         */ 
		public static function write($PHPSESSID, $data){
			$method=$data ? 'set' : 'replace';
			return  self::$handler->$method(self::session_key($PHPSESSID), $data, MEMCACHE_COMPRESSED, self::$lifetime);
		}
        /**
         * 注消
         * Enter description here ...
         * @param unknown_type $PHPSESSID
         */
		public static function destroy($PHPSESSID){
			return self::$handler->delete(self::$session_key($PHPSESSID));
		}
        /**
         * 清空
         * Enter description here ...
         * @param unknown_type $lifetime
         */
		public static function gc($lifetime){
			return true;
		}

		private static function session_key($PHPSESSID){
			return $PHPSESSID;
		}	
	}

?>